package io.renren.modules.sp.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.constant.Constant;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sp.dto.SpTeamDTO;
import io.renren.modules.sp.dto.SpTeamUserDTO;
import io.renren.modules.sp.dto.SpUserDTO;
import io.renren.modules.sp.entity.SpTeamEntity;
import io.renren.modules.sp.entity.SpTeamUserEntity;
import io.renren.modules.sp.entity.SpUserEntity;
import io.renren.modules.sp.service.*;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
* 领队成员
*
* @author Mark sunlightcs@gmail.com
* @since 3.0 2023-04-20
*/
@RestController
@RequestMapping("front/spteamuser")
@Api(tags="领队成员")
public class FrontTeamUserController extends FrontBaseController {

    @Autowired
    private SpTeamUserService spTeamUserService;
    @Autowired
    private SpTeamService spTeamService;
    @Autowired
    private SpUserService spUserService;
    @Autowired
    private SpTeamNumService spTeamNumService;

    @GetMapping("{id}")
    public Result<SpTeamUserDTO> get(@PathVariable("id") Long id){
        SpTeamUserDTO data = spTeamUserService.get(id);
        return new Result<SpTeamUserDTO>().ok(data);
    }

    /**
     * 调用场景：
     * 1、添加副领队- 不能带别的领队
     * 2、添加选手
     * 3、添加指导老师
     * @param dto
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody SpTeamUserDTO dto, HttpServletRequest request) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        SpUserDTO userDTO = this.getFrontUserInfo(request);

        //判断当前登录用户是否有代表队信息
        List<SpTeamUserEntity> list = spTeamUserService.queryList(
                new QueryWrapper<SpTeamUserEntity>()
                        .eq("user_id", userDTO.getId())
                        .in("type", 1, 2)
        );
        Long teamId = null;
        if (list != null && list.size() > 0) {
            teamId = list.get(0).getTeamId();
        }
        //判断当前用户是否有代表队
        List<SpTeamEntity>  teamList = spTeamService.queryList(
                new QueryWrapper<SpTeamEntity>()
                        .eq("creator", userDTO.getId())
        );
        if (teamList != null && teamList.size() > 0) {
            teamId = teamList.get(0).getId();
        }

        if (teamId == null) {
            return new Result().error("请先添加代表队");
        }

        dto.setTeamId(teamId);
        // 1领队 2副领队 3老师 4选手
        int type = dto.getType();

        if(type == 4){
            //判断省份的人数限制
            boolean isLimitNum = spTeamService.isLimitNum(teamId);
            if (!isLimitNum) {
                return new Result().error("代表队选手数量超出限额");
            }
        }

        String userTypeStr = "";
        switch (type) {
            case 2:
                userTypeStr = "副领队";
                break;
            case 3:
                userTypeStr = "老师";
                break;
            case 4:
                userTypeStr = "选手";
        }

        //指导老师是可以挂多个队伍的
        if (type == Constant.TeamUserType.LEADER_FU.getValue() || type == Constant.TeamUserType.STUDENT.getValue()) {
            // 验证副领队、选手是否参加其他代表队，指导老师是可以挂多个队伍的
            List<SpTeamUserEntity> teamUserList = spTeamUserService.queryList(
                    new QueryWrapper<SpTeamUserEntity>()
                            .eq("user_id", dto.getUserId())
                            .eq("type", type)
                            .ne("team_id", teamId)
            );
            if (teamUserList != null && teamUserList.size() > 0) {
                return new Result().error("该" + userTypeStr + "已经参加其他代表队");
            }
        }

        //保存副领队、选手、老师
        Result result = spTeamUserService.saveTeamUser(dto);
        if(!result.success()){
            return result;
        }

        // 修改领队的授权书
        if(type ==2 && StringUtils.isNotEmpty(dto.getEmpower())){
            SpUserEntity spUserEntity = spUserService.selectById(dto.getUserId());
            spUserEntity.setEmpower(dto.getEmpower());
            spUserService.updateById(spUserEntity);
        }

        return new Result();
    }

    @PostMapping("update")
    public Result update(@RequestBody SpTeamUserDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        spTeamUserService.update(dto);
        return new Result();
    }

    /**
     * 删除代表队成员，解除绑定
     */
    @PostMapping("delete")
    public Result delete(@RequestBody SpTeamUserDTO dto){
        return spTeamUserService.delTeamUser(dto.getUserId(), dto.getId());
    }

    /**
     * 设置成主领队
     * @param dto
     * @return
     */
    @PostMapping("setLeader")
    public Result updLeaer(@RequestBody SpTeamUserDTO dto){
        spTeamUserService.setLeader(dto.getTeamId(), dto.getId());
        return new Result();
    }


}
